package com.xnx3.wangmarket.plugin.ZuoxiBusy;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.xnx3.DateUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.actionLog.ElasticSearchMode;
import com.xnx3.kefu.core.bean.ChatUserBean;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.pluginManage.interfaces.MessageInterface;
import com.xnx3.kefu.core.util.KefuUtil;
import com.xnx3.kefu.core.util.MessageStorageUtil;
import com.xnx3.kefu.core.util.SocketUtil;
import com.xnx3.kefu.core.util.UserUtil;
import com.xnx3.kefu.core.vo.MessageReceiveVO;
import com.xnx3.kefu.core.vo.bean.MessageTypeEnum;

import cn.zvo.log.Log;
import cn.zvo.log.datasource.elasticsearch.ElasticSearchDataSource;
import cn.zvo.log.framework.springboot.LogUtil;
import io.netty.channel.Channel;
import net.sf.json.JSONObject;

/**
 * 离线消息自动回复，消息接口的实现
 * @author 管雷鸣
 *
 */
public class MessageInterfaceImpl implements MessageInterface{
	public static final String YUYUE_CURRENT_ZUOXI_LIST = "YUYUE_CURRENT_ZUOXI_LIST";	//获取当前客服的在线坐席列表
	public static final String YUYUE_OVER_SERVICE = "YUYUE_OVER_SERVICE";	//结束服务。用户socket还未断开，但是用户结束了服务，不再跟当前客服坐席对话了。
	public static final String YUYUE_PAIDUI_ADD = "YUYUE_PAIDUI_ADD";		//选中一个坐席，进入排队
	public static final String YUYUE_CONNECT_CHAT = "YUYUE_CONNECT_CHAT";		//客服坐席忙完一个后，会自动接通下一个，接通下一个就是服务器通过给下一个发送这个表示，用户客户端接收到后，自动打开会话窗口
	
	
	@Override
	public void offlineMessage(Channel channel, MessageReceiveVO message) {
	}

	@Override
	public void online(Channel channel) {
	}

	@Override
	public void offline(Channel channel) {
		//一个人离线，基本属于访客咨询完成触发。也有可能是客服网络中断导致离线
		
		//离线，那么坐席结束服务
		over_service(channel);
	}

	@Override
	public void autoReply(Channel channel, String otherChatId) {
		//自动回复，也就是建立对话窗口时就会触发
		
		//取出当前socket连接的用户信息
		ChatUserBean chatUserBean = SocketUtil.getUser(channel);
		
		/* 将两个人关联起来 */
		//当前socket用户
		chatUserBean.setBusy(true);
		chatUserBean.setOtherId(otherChatId);
		chatUserBean.setStartChatTime(DateUtil.timeForUnix13());
		SocketUtil.updateUser(channel, chatUserBean);
		
		//对方
		ChatUserBean otherChatUserBean = UserUtil.getUser(otherChatId);
		if(otherChatUserBean != null) { //开发环境会有这个情况，因为tomcat重启数据就没了，但浏览器缓存中还有这个用户
			otherChatUserBean.setBusy(true);
			otherChatUserBean.setOtherId(chatUserBean.getChatid());
			otherChatUserBean.setStartChatTime(DateUtil.timeForUnix13());
			UserUtil.updateUser(otherChatId, otherChatUserBean);
		}
		
	}

	@Override
	public boolean messageReceivedChat(Channel channel, MessageReceiveVO msg) {
		if(msg.getType().equalsIgnoreCase(MessageTypeEnum.CLOSE_SERVICE.name)) {
			//某一端发起结束服务
			over_service(channel);
		}
		return true;
	}
	
	//结束当前咨询服务，有的是直接用户关闭socket，有的是用户点击结束服务按钮但socket未断开
	public void over_service(Channel channel){
		
		//取出当前socket连接的用户信息
		ChatUserBean chatUserBean = SocketUtil.getUser(channel);
		if(chatUserBean == null){
			//这个情况不应该存在才是，既然来了，那证明已经连接过，有记录了
			//ConsoleUtil.error("over_service my channel chatUserbean is null channelid:"+SocketUtil.getChannelId(channel));
			return;
		}
		//判断当前状态是否是忙碌，也就是是否是跟别人在通话
		if(!chatUserBean.isBusy()){
			//没有跟别人通话，那离线就离线好了，对其他人没影响
			return;
		}
		
		//取到另一个人的信息
		ChatUserBean otherChatUserBean = UserUtil.getUser(chatUserBean.getOtherId());
		
		//取到客服坐席的chatuserbean
		ChatUserBean zuoxiChatUserBean = null;
		//游客（咨询者）的chatuserbean
		ChatUserBean youkeChatUserBean = null;	
		if(chatUserBean.getType().equalsIgnoreCase("user")){
			//是注册用户，那可能就是坐席了
			zuoxiChatUserBean = chatUserBean;
			youkeChatUserBean = otherChatUserBean;
		}else{
			//不是这个人，那就是另一个人了
			if(otherChatUserBean.getChatid() == null){
				ConsoleUtil.error("zuoxi null "+otherChatUserBean.toString());
			}
			zuoxiChatUserBean = otherChatUserBean;
			youkeChatUserBean = chatUserBean;
		}
		
		
		//将另一个人设置为空闲
		otherChatUserBean.setBusy(false);
		otherChatUserBean.setOtherId(null);
		otherChatUserBean.setStartChatTime(0);
		UserUtil.updateUser(chatUserBean.getOtherId(), otherChatUserBean);
		//将当前连接的用户进行设置，设置为清闲
		chatUserBean.setBusy(false);
		chatUserBean.setOtherId(null);
		chatUserBean.setStartChatTime(0);
		SocketUtil.updateUser(channel, chatUserBean);
		
		
		//如果没有使用es，那直接退出
		if(!LogUtil.isDataSource(ElasticSearchDataSource.class)) {
			return;
		}
		//将当前客服服务记录进行日志存储,如果使用了es的话
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("zuoxiChatId", zuoxiChatUserBean.getChatid());	//坐席客服的chatid
		params.put("otherChatId", youkeChatUserBean.getChatid());	//咨询用户的chatid
		params.put("zuoxiNickname", zuoxiChatUserBean.getNickname());	//坐席客服的昵称
		params.put("otherNickname", youkeChatUserBean.getNickname());	//坐席客服的昵称
		params.put("time", DateUtil.timeForUnix10());	//当前时间，消息产生的时间
		int serverTime = (int) ((DateUtil.timeForUnix13() - zuoxiChatUserBean.getStartChatTime())/1000);	//将单位毫秒转变为秒
		params.put("serviceTime", serverTime);	//坐席客服服务用户的时间
		Kefu kefu = KefuUtil.getKefu(zuoxiChatUserBean.getChatid());
		if(kefu != null){
			params.put("kefuid", kefu.getId());	//当前坐席属于哪个客服平台
		}
		
//		//取出当前服务客户收发消息的条数 
//		//客服发送的条数
//		int kefuSendCount = count("select count(*) from "+MessageStorageUtil.logstore+" WHERE sendId='"+zuoxiChatUserBean.getChatid()+"' AND receiveId='"+youkeChatUserBean.getChatid()+"' AND time > "+(zuoxiChatUserBean.getStartChatTime()-1));
//		//客服接收的条数，也就是游客发送的条数
//		int kefuReceiveCount = count("select count(*) from "+MessageStorageUtil.logstore+" WHERE sendId='"+youkeChatUserBean.getChatid()+"' AND receiveId='"+zuoxiChatUserBean.getChatid()+"' AND time > "+(zuoxiChatUserBean.getStartChatTime()-1));
//		params.put("zuoxiSendCount", kefuSendCount);
//		params.put("zuoxiReceiveCount", kefuReceiveCount);
//		
//		if(kefuSendCount > 0 || kefuReceiveCount > 0){
//			//有沟通记录，才记录沟通日志
//			com.xnx3.wangmarket.plugin.serviceLog.MessageInterfaceImpl.getLog().add(params);
////			ConsoleUtil.debug(JSONObject.fromObject(params).toString());
//		}
		
		
//		
//		
//		//将当前客服服务记录进行日志存储,如果使用了es的话
//		if(ElasticSearchMode.es != null){
//			try {
//				Map<String, Object> params = new HashMap<String, Object>();
//				params.put("zuoxiChatId", zuoxiChatUserBean.getChatid());	//坐席客服的chatid
//				params.put("otherChatId", youkeChatUserBean.getChatid());	//咨询用户的chatid
//				params.put("zuoxiNickname", zuoxiChatUserBean.getNickname());	//坐席客服的昵称
//				params.put("otherNickname", youkeChatUserBean.getNickname());	//坐席客服的昵称
//				params.put("time", DateUtil.timeForUnix10());	//当前时间，消息产生的时间
//				int serverTime = (int) ((DateUtil.timeForUnix13() - zuoxiChatUserBean.getStartChatTime())/1000);	//将单位毫秒转变为秒
//				params.put("serviceTime", serverTime);	//坐席客服服务用户的时间
//				Kefu kefu = KefuUtil.getKefu(zuoxiChatUserBean.getChatid());
//				if(kefu != null){
//					params.put("kefuid", kefu.getId());	//当前坐席属于哪个客服平台
//				}
//				
//				//取出当前服务客户收发消息的条数
//				//客服发送的条数
//				int kefuSendCount = count("select count(*) from "+MessageStorageUtil.logstore+" WHERE sendId='"+zuoxiChatUserBean.getChatid()+"' AND receiveId='"+youkeChatUserBean.getChatid()+"' AND time > "+(zuoxiChatUserBean.getStartChatTime()-1));
//				//客服接收的条数，也就是游客发送的条数
//				int kefuReceiveCount = count("select count(*) from "+MessageStorageUtil.logstore+" WHERE sendId='"+youkeChatUserBean.getChatid()+"' AND receiveId='"+zuoxiChatUserBean.getChatid()+"' AND time > "+(zuoxiChatUserBean.getStartChatTime()-1));
//				params.put("zuoxiSendCount", kefuSendCount);
//				params.put("zuoxiReceiveCount", kefuReceiveCount);
//				
//				if(kefuSendCount > 0 || kefuReceiveCount > 0){
//					//有沟通记录，才记录沟通日志
//					ElasticSearchMode.es.put(params, com.xnx3.wangmarket.plugin.serviceLog.MessageInterfaceImpl.INDEX);
//					ConsoleUtil.debug(JSONObject.fromObject(params).toString());
//				}
//				
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		
		
	}
	

    /**
     * @param countSql 统计的sql语句，传入格式如： 
     * 	<pre>
     * select count(*) from useraction WHERE time > 1624001953
     * 	</pre>
     * @return 执行统计语句所获取到的结果，返回值为int类型
     */
    public int count(String countSql){
//    	ElasticSearchDataSource datasource = (ElasticSearchDataSource) com.xnx3.wangmarket.plugin.serviceLog.MessageInterfaceImpl.getLog().getDatasource();
//    	List<Map<String, Object>> list = datasource.es.searchBySqlQuery(countSql);
//    	int count = (Integer) list.get(0).values().stream().findAny().get();
//	    return count;
    	return 0;
    }
}
